<?php
namespace addon\wechat_config\logic;
// +----------------------------------------------------------------------
// | Author: xiaojun <920668625@qq.com>
// +----------------------------------------------------------------------
use app\common\logic\LogicBase;
use think\Db;
use \tpfcore\Core;
use tpfcore\web\Curl;
use think\Cache;
use tpfcore\helpers\StringHelper;

class WechatConfig extends LogicBase
{
	public function getWechatConfig($data=['limit'=>1]){
		return self::getList($data);
	}

	public function getWechatConfigInfo($data=[],$field = true){
		$info   = $this->where($data)->order('id desc')->find();
		if(empty($info)) return $info;
		$result = json_decode($info['value'],true);
		$result['id'] = $info['id'];
		return $result;
	}

	public function saveWechatConfig($data){
		$scene = isset($data['id']) && !empty($data['id']) ? 'edit' : 'add';
		if($scene == 'edit'){
			$id     = $data['id'];
			unset($data['id']);
			$data   = json_encode($data,JSON_UNESCAPED_UNICODE);
			$result = $this->save(['value'=>$data],['id'=>$id]);
		}else{
			$data   = json_encode($data,JSON_UNESCAPED_UNICODE);
			$result = $this->insert(['value'=>$data]);
		}
		$result = ($result === false) ? false : true;
		return $result ? [RESULT_SUCCESS,'修改成功'] : [RESULT_ERROR,'修改失败'];
	}
	// 获取jspapi须要的参数
	public function getJsapiParam($data){
		$info = Db::name('WechatConfig')->order('id desc')->value('value');
        $info = json_decode($info,true);

    	if(empty($info) || empty($info['wechat_appid']) || empty($info['wechat_appsecret'])){
    		throw new \Exception("请先配置好微信公众号");exit;
    	}
    	$appid     = $info['wechat_appid'];
        $appsecret = $info['wechat_appsecret'];
    	$jsapiTicket = $this->getJsApiTicket();

    	/* 基本参数开始 */
    	$url =$data['url'];  // 从数据传递过来
    	$timestamp = time();
    	$nonceStr=StringHelper::get_random_string(16);

    	$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    	$signature = sha1($string);

    	$signPackage = array(
	      "appId"     => $appid ,
	      "nonceStr"  => $nonceStr,
	      "timestamp" => $timestamp,
	      "url"       => $url,
	      "signature" => $signature,
	      "rawString" => $string,
	      "access_token"=>WechatFunc::getAccessToken()
	    );
	    return [0,"success",$signPackage];
	}
	private function getJsApiTicket(){
		if(Cache::has('wx_jsapi_ticket')){
            $data = json_decode(Cache::get('wx_jsapi_ticket'));
            $ticket = $data->jsapi_ticket;
        }else{
        	$access_token = WechatFunc::getAccessToken();
        	$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$access_token";
        	$res = json_decode(Curl::get($url));
        	$ticket = $res->ticket;
        	if ($ticket) {
        		$data['expire_time'] = time() + 7200;
	        	$data['jsapi_ticket'] = $ticket;
	        	Cache::set('wx_jsapi_ticket',json_encode($data),7200);
        	}

        }
        return $ticket;
	}
}